<template>
  <ElCard
    :class="['mb-6', !visibleForm && 'py-0 !mb-0']"
    :body-class="`transition-all duration-300 !pb-0 ${!visibleForm && '!py-0'}`"
  >
    <PowerfulForm
      ref="PForm"
      extend-table
      show-type="query"
      :property="{
        inline: true,
      }"
    >
      <template #last-item>
        <el-button
          type="primary"
          @click="PTable?.resetList(PForm?.powerfulFormData.formData || {})"
        >
          查询
        </el-button>
        <el-button @click="PForm?.resetForm">重置</el-button>
      </template>
    </PowerfulForm>
  </ElCard>

  <ElCard>
    <PowerfulTable
      ref="PTable"
      :btn-config="btnConfig"
      :header="headers"
      :list-request="{
        listApi: muscleApi.getMuscleList,
        listQuery: {
          parent_id: '0',
        },
      }"
      :property="{
        rowKey: '_id',
      }"
      @btn-plus-refresh="handleVisibleForm(PForm?.visibleFormTrigger)"
      @btn-click="handleBtnClick"
      @btn-plus-change="handleBtnPlusChange"
    >
    </PowerfulTable>
  </ElCard>

  <ElDrawer
    v-model="drawerData.visible"
    :title="drawerData.showType === 'add' ? '新增肌群' : '编辑肌群'"
  >
    <PowerfulForm
      ref="DrawerPForm"
      extend-table
      :form-data-default="drawerData.formData"
      :show-type="drawerData.showType"
      :apis="{
        add: muscleApi.muscleAdd,
        edit: muscleApi.muscleUpdate,
      }"
      :property="{
        labelWidth: '100px',
      }"
    />

    <template #footer>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import {
  FormTypeEnum,
  type PowerfulFormExpose,
  type PowerfulFormPTHeaders,
} from 'el-plus-powerful-form'
import type {
  Handlers,
  PowerfulTableBaseProps,
  PowerfulTableExpose,
} from 'el-plus-powerful-table'
import { muscleApi } from '@/api/muscle'
import { useListOperate } from '@/hooks/useListOperate'

type Rows = any
const { proxy } = getCurrentInstance()!
const PTable = ref<PowerfulTableExpose | null>(null)
const PForm = ref<PowerfulFormExpose | null>(null)
const DrawerPForm = ref<PowerfulFormExpose | null>(null)
const drawerData = reactive({
  visible: false,
  showType: 'add',
  formData: {},
})

const { headerOperateColumn, btnConfig, visibleForm, handleVisibleForm } =
  useListOperate<Rows>()

const headers = reactive([
  {
    label: '隶属部位',
    props: {
      type: 'text',
      prop: 'parent_id',
      filters: [],
      formItem: {
        type: FormTypeEnum.Select,
        defaultData: '0',
      },
    },
  },
  {
    label: '肌肉名称',
    props: {
      prop: 'title',
      formItem: {
        rule: true,
      },
    },
  },
  {
    label: '排序',
    props: {
      prop: 'sort',
      formItem: {
        rule: true,
        showType: ['add', 'edit'],
      },
    },
  },
  headerOperateColumn,
] satisfies PowerfulFormPTHeaders<Rows>[])

// 读取独立肌群列表
muscleApi
  .getMuscleList({
    pageIndex: 0,
    pageSize: 0,
    parent_id: '0',
  })
  .then(res => {
    ;(headers[0].props as PowerfulTableBaseProps).filters = [
      {
        key: '0',
        value: '独立部位',
      },
      ...res.data.data.map((item: { title: string; _id: string }) => ({
        key: item._id,
        value: item.title,
      })),
    ]

    PForm.value?.refreshRender('PTable', proxy!)
  })

// 表格右侧操作按钮
const handleBtnClick: Handlers['btn-click'] = async ({ row, params }) => {
  if (params.emit === 'delete') {
    const { data } = await muscleApi.muscleDelete({
      ids:[row._id]
    })
    setTimeout(() => PTable.value?.resetList(), 300)
    return
  }

  if (params.emit === 'update') {
    drawerData.visible = true
    drawerData.showType = 'edit'
    drawerData.formData = { ...row }
    return
  }

  if (params.emit === 'view') {
    const { data } = await muscleApi.getMuscleList({
      pageIndex: 0,
      pageSize: 0,
      parent_id: row._id,
    })
    if (data.data.length) {
      row.children = data.data
    } else {
      row.hasChildren = false
    }
    return
  }
}

// 表格顶部操作按钮
const handleBtnPlusChange: Handlers['btn-plus-change'] = payload => {
  if (payload.effect === 'add') {
    drawerData.visible = true
    drawerData.showType = 'add'
  }
}

// 侧边栏表单提交按钮
const handleSubmit = async () => {
  if (drawerData.showType === 'add') {
    await DrawerPForm.value?.submitForm({}, {})
    setTimeout(() => PTable.value?.resetList(), 300)
    drawerData.visible = false
  }
  if (drawerData.showType === 'edit') {
    await DrawerPForm.value?.submitForm({}, {})
    setTimeout(() => PTable.value?.resetList(), 300)
    drawerData.visible = false
  }
}
</script>

<style scoped></style>
